package app.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JProgressBar;

public class AppUtilities extends AbsAppUtilities {

	public AppUtilities(File file) throws IOException {
		super(file);
	}

	public void doMerging(String fileName, JProgressBar jProgressBar) {
		StringBuffer strBuf = new StringBuffer();
		Scanner scanner = null;
		boolean firstLine = true;
		int statusInt = 0;
		FileWriter fileWriter = null;

		try {
			// read from file
			for(File file : this.files) {
				// ignore output file if it is existed
				if(file.getName().equalsIgnoreCase(fileName)) {
					continue;
				}

				scanner = new Scanner(file);
				if(firstLine && scanner.hasNextLine()) {
					// get first line at one time
					firstLine = false;
					strBuf.append(scanner.nextLine() + "\n");
				}
				else { // ignore first line
					scanner.nextLine();
				}
				while (scanner.hasNextLine()) {
					strBuf.append(scanner.nextLine() + "\n");
				}

				// increase status bar
				jProgressBar.setValue(++statusInt);
			}

			// save the merged content to disk
			fileWriter = new FileWriter(new File(getLastLocation() + "/" + fileName));
			fileWriter.write(strBuf.toString());

			// closing
			fileWriter.close();
			scanner.close();
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}

		// store file name to property file
		fileName = fileUtilities.removeExtension(fileName);
		this.prop.setProperty(LAST_FILENAME, fileName);
	}
}
